//
//  AFHttp.swift
//  BellManage
//
//  Created by Bestsch on 16/6/12.
//  Copyright © 2016年 wsl. All rights reserved.
//

import Foundation

/**
 AFNetworking封装post
 
 - parameter url:        接口地址
 - parameter requestXML: xml字符串
 - parameter finished:   回调方法
 */
func HttpPostURL(_ url: String!,requestXML: String!,finished:@escaping (_ data: Data?,_ result: String?,_ error: NSError?)->()) {
    //    print("\(url)\n\(requestXML)")
    let request: NSMutableURLRequest = NSMutableURLRequest.init()
    request.url = URL.init(string: url)
    request.httpBody = requestXML.data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
    request.setValue("text/xml", forHTTPHeaderField: "Content-Type")
    
    let operation: AFHTTPRequestOperation = AFHTTPRequestOperation.init(request: request as URLRequest)
    operation.setCompletionBlockWithSuccess({ (operation, response) in
        
        let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
        var resultstr: String = String.init(data: response as! Data, encoding: String.Encoding(rawValue: enc))!
        print("接口返回:\(resultstr)")
        resultstr = resultstr.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ")
        
        finished(response as? Data,resultstr,nil)
        
        }) { (operation, error) in
            let dic: NSDictionary = error._userInfo as! NSDictionary
            let enc = CFStringConvertEncodingToNSStringEncoding(UInt32(CFStringEncodings.GB_18030_2000.rawValue))
            let str = String.init(data: dic.object(forKey: "com.alamofire.serialization.response.error.data") as! Data, encoding: String.Encoding(rawValue: enc))
            print("接口错误：\(str),接口地址:\(url),传递字符串:\(requestXML)")
            
            finished(nil,nil,error as NSError?)
    }
    
    operation.start()
}
/**
 AFNetworking封装post－－UTF8格式
 
 - parameter url:        接口地址
 - parameter requestXML: xml字符串
 - parameter finished:   回调方法
 */
func HttpPostUTF(_ url: String!,requestXML: String!,finished:@escaping (_ data: Data?,_ result: String?,_ error: NSError?)->()) {
    
    let request: NSMutableURLRequest = NSMutableURLRequest.init()
    request.url = URL.init(string: url)
    request.httpBody = requestXML.data(using: String.Encoding.utf8)
    request.httpMethod = "POST"
    request.setValue("text/xml", forHTTPHeaderField: "Content-Type")
    
    let operation: AFHTTPRequestOperation = AFHTTPRequestOperation.init(request: request as URLRequest)
    operation.setCompletionBlockWithSuccess({ (operation,responseObject) in
        var resultstr: String = String.init(data: responseObject as! Data, encoding: String.Encoding.utf8)!
        
        resultstr = resultstr.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").replacingOccurrences(of: "\n", with: "\\n").replacingOccurrences(of: "\t", with: " ").replacingOccurrences(of: "null", with: "\"\"")
        print("接口返回:\(resultstr)")
        finished(responseObject as? Data,resultstr,nil)
        
    }) {
        (operation,error) in
        let dic: NSDictionary = error._userInfo as! NSDictionary
        let data = dic.object(forKey: "com.alamofire.serialization.response.error.data")
        if data != nil {
            let str = String.init(data: data as! Data, encoding: String.Encoding.utf8)
            print("接口错误：\(str),接口地址:\(url),传递字符串:\(requestXML)")
        }else {
            print("接口错误：\(error.localizedDescription),接口地址:\(url),传递字符串:\(requestXML)")
        }
        
        finished(nil,nil,error as NSError?)
        
    }
    
    operation.start()
}

enum Method: Int {
    case POST
    case GET
}

/**
 afn传递字典的http请求
 
 - parameter method:  post,get传输数据
 - parameter url:     接口地址
 - parameter param:   字典
 - parameter Success: 成功
 - parameter Failure: 失败
 */
func AFNRequestWithMethod(method: Method,
                          url: String!,
                          param: NSDictionary,
                          Success: @escaping (_ response: Any?) -> (),
                          Failure: @escaping (_ error: NSError?) -> ()) {
    
    let baseUrl = NSURL(string: url)
    let manage = AFHTTPSessionManager(baseURL: baseUrl as URL?)
    manage.responseSerializer.acceptableContentTypes?.insert("text/html")
    manage.responseSerializer.acceptableContentTypes?.insert("text/plain")
    
    
    switch method {
    case .POST:
        
        
        manage.post(url, parameters: param, success: { (dataTask, response) in
            
            Success(response)
            }, failure: { (dataTask, error) in
                Failure(error as NSError)
        })
        break
    case .GET:
        manage.get(url, parameters: param, success: { (dataTask, response) in
            Success(response)
            }, failure: { (dataTask, error) in
                Failure(error as NSError)
        })
        break
    }
}


